#!/usr/local/bin/python2.5


from copy import copy
from remote import *
from time import *
from dDS_clnt import *


mapping = {6 : 0,
           1 : 1,
           2 : 2,
           3 : 3,
           4 : 4,
           5 : 5,
           7 : 6,
           8 : 7}


rpa = remotePhasedArray()
dds = DDSClient('128.171.116.189')


  #
  # 
  # Timing
 ### 
  # 

def waitUntil(time_str):
    """time_str: default time formatting"""
    #print "Waiting until %s!" %time_str
    return_at = mktime(strptime(time_str))
    while time() < return_at:
        pass

  #
 ### 
  # Timing
  # 
  # 


  #
  # 
  # Antenna Inclusion
 ### 
  # 

def removeAll():
    print "Removing all antennas from the sum!"
    rpa.setGains(GZERO)
    #print "Gains set to:", GZERO

def includeOnly(ant):
    #print "Including only antennas %d in the sum!" %mapping[ant]
    GNEW = GZERO.copy()
    for a in ant:
        GNEW[mapping[a]] = 128
    rpa.setGains(GNEW)
    #print "Gains set to:", GNEW

def only6(): includeOnly(0)
def only1(): includeOnly(1)
def only2(): includeOnly(2)
def only3(): includeOnly(3)
def only4(): includeOnly(4)
def only5(): includeOnly(5)
def only7(): includeOnly(6)
def only8(): includeOnly(7)

  #
 ### 
  # Antenna Inclusion
  # 
  # 


  #
  # 
  # Delay Tracking
 ### 
  # 

D2000 = {0:2000.0, 1:2000.0, 2:2000.0, 3:2000.0, 4:2000.0, 5:2000.0, 6:2000.0, 7:2000.0}

def resetDelays():
    #print "Resetting delays to 2000ns!"
    rpa.setDelays(D2000)
    #print rpa.getDelays()

def startDelayTracking():
    print "Starting delay tracking!"

def stopDelayTracking():
    print "Stopping delay tracking!"

  #
 ### 
  # Delay Tracking
  # 
  # 


AFALSE = (False, False, False, False, False, False,
          False, False, False, False, False)
ZERO = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
N = [False, True, True, True, False, True, False, True, True, False, False]

def scan( No, # scan number
          Time, # start of scan
          Duration, # in seconds
          PAnt, # phased array antenna
          CAnt, # comparison antenna
          Conf, # configuration string
          ):

    pap_ant = PAnt
    pap_opt = Conf
    com_ant = CAnt

    print 
    print "###############################################"
    confstr = ''.join([str(a) for a in pap_ant]) + \
              ''.join(Conf) + '(x)' +str(com_ant)
    print "SCAN NO %d ---> %s" %(No,confstr)
    print "STARTS:", Time
    print

    ROT = copy(N)
    WAL = copy(N)

    print "PHASED-ARRAY SUM CONSISTS OF", pap_ant
    includeOnly(pap_ant)

    if "A" in pap_opt:
        rpa.pa.root.startTracking()
        print "  (D)ELAY TRACKING:   ON"
        print "  (F)RINGE STOPPING:  ON"
        print "  (W)ALSHING:         ON"
    elif "W" in pap_opt:
        rpa.pa.root.stopTracking()
        sleep(5)
        resetDelays()
        print "  (D)ELAY TRACKING:  OFF"
        for a in pap_ant:
            ROT[a] = False
        print "  (F)RINGE STOPPING: OFF"
        print "  (W)ALSHING:         ON"
    else:
        rpa.pa.root.stopTracking()
        sleep(5)
        resetDelays()
        print "  (D)ELAY TRACKING:  OFF"
        for a in pap_ant:
            ROT[a] = False
        print "  (F)RINGE STOPPING: OFF"
        for a in pap_ant:
            WAL[a] = False
        print "  (W)ALSHING:        OFF"

    print "COMPARISON ANTENNA IS ", com_ant

    dds.ddsSetRotators(ROT)
    dds.ddsSetWalshers(WAL)
    print "SETUP DONE!"
    print

    waitUntil(Time)
    print "START:", asctime(gmtime())

    #print "WALSH BITS"
    #a = rpa.getCapture(32)
    
    waitUntil( asctime(gmtime(mktime(strptime(Time)) + Duration)))
    print "STOP:", asctime(gmtime())
    print "###############################################"

    waitUntil( asctime(gmtime(mktime(strptime(Time)) + Duration + 5)))
    

if __name__ == "__main__":

    import sys
    if len(sys.argv) == 2:
        START_AT = int(sys.argv[1])
    elif len(sys.argv) == 3:
        START_AT = int(sys.argv[2])
        SKD_FILE = open(sys.argv[1])
        print "READING FROM FILE %s" %SKD_FILE
    else:
        START_AT = 1

    from parse_skd import parse_skd
    SCANS = parse_skd(SKD_FILE)

    print
    print "###############################################"
    print "STARTING SCHEDULE AT SCAN %d" %START_AT
    print "TOTAL SCANS", len(SCANS)
    START = mktime(strptime(SCANS[0]['time']))
    STOP = mktime(strptime(SCANS[-1]['time']))
    print "TOTAL TIME %.2f minutes" %((STOP-START)/60.)
    print

    #removeAll()
    OFF = list(ZERO)
    OFF[4] = 117
    dds.ddsSetOffsets(OFF)
    
    #exit()

    DUR = 120
    for n in range(START_AT-1,len(SCANS)):
        scan(n+1, SCANS[n]['time'], DUR, SCANS[n]['pant'],
             SCANS[n]['comp'], SCANS[n]['conf'])

    print "SCHEDULE ENDED AT", asctime(gmtime())

